package monarc.jscheduler.dag;

import edu.uci.ics.jung.graph.impl.DirectedSparseGraph;
import monarc.jscheduler.dag.StatusCatalog;
import monarc.jscheduler.dag.graph.Nod;
import monarc.jscheduler.dag.ReschedulingProcedure;
import monarc.center.Farm;

/**
 * 
 * @author Alexandra Olteanu
 *
 */
public class MonitorJob extends Thread {
	
	public StatusCatalog catalog;
	public String algorithm;
	public ReschedulingProcedure replan;
	public DirectedSparseGraph tasks;
	
	/**
	 *  Constructor
	 */
	public MonitorJob(){
		super();
	}
	
	/**
	 * Constructor
	 * @param catalog tasks catalog
	 */
	public MonitorJob(StatusCatalog catalog, DirectedSparseGraph g){
		super();
		this.replan = new ReschedulingProcedure();
		this.tasks = g;
		this.catalog = catalog;	
	}
	
	/**
	 * This method returns the tasks catalog
	 * @return catalog
	 */
	public StatusCatalog getCatalog(){
		return catalog;
	}
	
	/**
	 * This method sets the catalog
	 * @param catalog
	 */
	public void setCatalog(StatusCatalog catalog){
		this.catalog = catalog;
	}
	
	/**
	 * This method set the tasks graph
	 * @param g
	 */
	public void setGraph(DirectedSparseGraph g){
		this.tasks = g;
	}
	
	/**
	 * 
	 * @param farm
	 */
	public void setFarm(Farm farm){
		//if(replan != null)
			replan.setFarm(farm);
	}
	
	/**
	 *  This method sets the parameters used for rescheduling 
	 *  and starts the rescheduling procedure 
	 */
	public void rescheduling(){
		Nod node = catalog.getNodeInError();
		replan.setAlgoritmToUse(algorithm);
		replan.setCatalog(catalog);
		replan.setGraph(tasks);
		if(node != null){
			catalog.changeStatus(node.index, 2);
			replan.reschedule(node);
		}
	}
	
	/**
	 * 
	 * @param algorithm
	 */
	public void setAlgorithm(String algorithm){
		this.algorithm = algorithm;
	}
	
	/**
	 * The run method
	 */
	public void run(){
		
		Integer fin_nr = 0;
		Integer err_nr = 0;
		while(fin_nr< catalog.taskStatus.size()){
			fin_nr = catalog.nrOfFinishedJobs();
			err_nr = catalog.nrOfErrorJobs();
			//catalog.printCatalog();
			try{
				sleep(20);
				}
			catch(InterruptedException e) {
				System.out.println("Sleeping error!:)");
			}
			if(err_nr > 0){
				// aici se apeleaza procedura de replanificare
				rescheduling();
			}
		}
		System.out.println("Stop monitoring the task graph!!!");
		this.stop();	
	}
	
} // end of class MonitorJob